package com.ailanyin.admin.modules.system.controller;


import cn.hutool.core.util.ObjectUtil;
import com.ailanyin.common.exception.ApiException;
import com.ailanyin.common.result.AjaxResult;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 *
 * @author ailanyin
 * @version 1.0
 * @since 2021/10/15 0015 下午 16:43
 */
@ControllerAdvice
public class BaseExceptionController {

    /**
     * 非自定义异常
     * 存进数据库
     *
     * @param e Exception
     * @return AjaxResult
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public AjaxResult error(Exception e) {
        e.printStackTrace();
        return AjaxResult.error(e.getMessage());
    }

    /**
     * 自定义异常, 控制台不打印
     *
     * @param e ApiException
     * @return AjaxResult
     */
    @ExceptionHandler(ApiException.class)
    @ResponseBody
    public AjaxResult handlerApiException(ApiException e) {
        return AjaxResult.error(e.getMessage());
    }

    /**
     * 无权限访问异常, 控制台不打印
     *
     * @param e AccessDeniedException
     * @return AjaxResult
     */
    @ExceptionHandler(AccessDeniedException.class)
    @ResponseBody
    public AjaxResult handlerAccessDeniedException(HttpServletRequest request, AccessDeniedException e) {
        return AjaxResult.noPermissionResult(ObjectUtil.isNotEmpty(request) ? request.getRequestURI() : null);
    }
}
